﻿/*--------------------------------------------------------------
 * Author : Shine K Velayudhan 
 ---------------------------------------------------------------*/
using System;
using System.Collections.Generic;

namespace IQN.Logging
{
    internal sealed class MessageCache<TMessage> where TMessage :LogMessage
    {
        private int cacheSize;
        private readonly object fifoLock;
        private readonly Queue<TMessage> fifoQeue;
        private const int MAX_CacheSize = 1024;

        internal MessageCache(int cacheSize)
        {
            this.fifoQeue = null;
            this.fifoLock = new object();
            this.cacheSize = 1;
            this.cacheSize = Math.Max(cacheSize, 1);
            this.cacheSize = Math.Min(cacheSize, MAX_CacheSize);
            this.fifoQeue = new Queue<TMessage>(this.cacheSize);
        }
        internal void Clear()
        {
            lock (this.fifoLock)
            {
                this.fifoQeue.Clear();
            }
        }
        internal IEnumerable<TMessage> GetSnapshotOfMessages()
        {
            lock (this.fifoLock)
            {
                return new List<TMessage>(this.fifoQeue);
            }
        }
        internal void QueueMessage(TMessage message, bool removeOldMessageIfFull)
        {
            if (null != message)
            {
                lock (this.fifoLock)
                {
                    if (IsFull)
                    {
                        if (!removeOldMessageIfFull)
                        {
                            return;
                        }
                        this.fifoQeue.Dequeue();
                    }
                    this.fifoQeue.Enqueue(message);
                }
            }
        }
        internal bool IsFull
        {
            get
            {
                return (this.fifoQeue.Count >= this.cacheSize);
            }
        }
    }
}
